package com.hao.tool.common.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Created by haol on 2017/3/16.
 */
public class CookieUtil {

    private static Logger logger = LoggerFactory.getLogger(CookieUtil.class);


    public static HttpServletResponse saveCookie(HttpServletResponse response,
                                                 String cookieName, String cookieValue) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);
        // logger.info("保存cookie到本地,name =[{}]",cookieName);
        return response;
    }

    public static HttpServletResponse deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return response;
    }

    private static Cookie getCookieByName(HttpServletRequest request, String name) throws Exception {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie_ : cookies) {
            if (cookie_.getName().equals(name)) {
                return cookie_;
            }
        }
        throw new Exception("cookie信息不存在");
    }

    public static String getTokenValueByCookie(HttpServletRequest request, String name) {
        try {
            Cookie cookie = getCookieByName(request, name);
            return cookie.getValue();
        } catch (Exception e) {
            return null;
        }
    }


    public static HttpServletResponse updateCookie(String cookieName, String token,
                                                   HttpServletResponse response) {
        // logger.info("更新cookie到本地,name =[{}],value=[{}]");
        return CookieUtil.saveCookie(response, cookieName, token);
    }

}


